<?php
class SupplierAction extends CommonAction {
	
	
	public function _initialize()
    {
        parent::_initialize();
        $this->suppierids = M('Supplier_user')->Field('supplier_id')->where(array('user_id' => session(C('USER_AUTH_KEY'))))->buildSql();
        $this->is_suppierids = M('Supplier_user')->Field('supplier_id')->where(array('user_id' => session(C('USER_AUTH_KEY'))))->count();

    }
	function index(){
        $pagesize = 10;
        if ($this->_get('pagesize')) {
            $pagesize = $this->_get('pagesize');
        }
        $listmap = 's.site_id = '.$this->siteid;

        if ($this->_get('type')) {
            $listmap .=' and s.type = '.$this->_get('type');
            if($this->_get('type')==0){
                $this->type='2';
            }else{
                $this->type=$this->_get('type');
            }
        }
        $myid=D('User')->where(' id = '.session(C('USER_AUTH_KEY')))->getField('member_id');
        $this->levelnum=D('Member')->where('id = '.$myid)->getField('level');
		
		if (!session(C('ADMIN_AUTH_KEY'))) {
		    if($this->levelnum == 1){
                $supplierid=M('Supplier')->where('member_id = '.$myid)->getField('id');
                $listmap .=" and s.member_id = ".$myid;
            }elseif($this->is_suppierids > 0) {
                $listmap .= ' and s.id in(' . $this->suppierids . ')';
            }
            //$this->suppier = M('Supplier')->where('site_id=' . $this->siteid . ' and id in(' . $this->suppierids . ')')->select();
        }
        if($_GET['keywords']!=''){
		    $listmap .=' and ( s.susername like "%'.$_GET['keywords'].'%" or m.id like "%'.$_GET['keywords'].'%" or m.nickname like "%'.$_GET['keywords'].'%" ) ';
		    $this->keywords=$_GET['keywords'];
        }
        $orderDB = D('Supplier');
        $count = $orderDB->alias('s')->where($listmap)->join('__MEMBER__ m on m.id = s.member_id')->join('__MEMBER__ n on n.id = s.aff_id')->count();
        //实例化分页类
        import('ORG.Util.Page');
        $p = new Page($count, $pagesize);

        $list = $orderDB->alias('s')->where($listmap)->join('__MEMBER__ m on m.id = s.member_id')->join('__MEMBER__ n on n.id = s.aff_id')->limit($p->firstRow . ',' . $p->listRows)-> Field("s.*,m.nickname as membername,m.id as membernumber,n.nickname as affname,m.money as money") ->order('id desc')->select();
		$pages = $p->show();
		if($_REQUEST['member_id']) {
			$this->member_id=$_REQUEST['member_id'];
		}
		$this->assign('list', $list);
		$this->assign('pages', $pages);
		$this->display();
	}
	//选择管理用户
	public function selectUser(){
		$this->listmap = 1;
//		var_dump(session(C('USER_AUTH_KEY')));
		if(!session(C('ADMIN_AUTH_KEY'))){
		    $this->listmap .= " and (pid = '".session(C('USER_AUTH_KEY') )."' or id = '".session(C('USER_AUTH_KEY') )."')";
		}
		$this->dao = D('User');
		parent::_list();
		$this->dao = D('Supplier');
		//当前站点
		$this->info = $this->dao -> where(array('id' => $this->_get('id'))) ->find();
		$curUserList = $this->dao ->alias('s') -> join("left join __SUPPLIER_USER__ as su on su.supplier_id = s.id") -> join("left join __USER__ as u on u.id = su.4")->Field('u.*,s.id as site_id')->where(array('s.id' => $this->_get('id'),'su.user_id' => array('gt',0))) -> select();
		$this->assign('curUserList',$curUserList);
		$this->display();
	}



    public function addconnect($mid,$rid){
        D('Member_connect')->data(array('member_id'=>$mid,'referee_id'=>$rid,'type'=>6))->add();
        $sc=D('Member')->where('id = '.$this->memberInfo['id'])->getfield('is_subscribe');
        $data=array('member_id'=>$mid,'smember_id'=>$rid,'level'=>'0','site_id'=>'143','deep'=>'1','is_subscribe'=>$sc,'datetime'=>time(),'oldid'=>'0');
        $a=D('Member_member')->data($data)->add();
    }
	
	
	//写入数据
    public function insert($data = '', $jumpUrl = '') {
        if (!isset($_POST)) {
            $this->error('请填写信息再提交');
            exit;
        }
		$_POST['area'] = ','.implode(',',$_POST['area']).',';
		$_POST['datetime'] = time();
		if($jumpUrl == ''){
			$jumpUrl = (session('jumpUrl')&&session('jumpUrl')!='') ? session('jumpUrl') : U('Admin/' . MODULE_NAME . '/index');
		}
        
        if ($this->dao->create($data)) {
            $result = $this->dao->add();
            if (false !== $result) {
				
				$member['username'] = 'user'.time();
				$member['password'] = md5(rand(000000, 999999));
				$member['nickname'] = $_POST['susername'];
				$member['level'] = 1;
				$member['site_id'] = 143;
				$member['id'] = M('Member') -> add($member);
				
				
				$this->dao -> where(array('id' => $result)) -> save(array('member_id' => $member['id']));
				
				$this->dao->create1($result, 1, $member, 143, 0);
				
                $this->success('操作成功', $jumpUrl);
            } else {
                $this->error($this->dao->getError());
            }
        } else {
            $this->error($this->dao->getError());
        }
    }
	
	
	

	public function myinsert(){
		$_POST['area'] = ','.implode(',',$_POST['area']).',';
		$_POST['datetime'] = time();
		$jumpUrl=U('Supplier/show');
		parent::insert($_POST,$jumpUrl);
	}
	//删除供货商同时要清空与管理者相关的记录
	public function delete(){
		M('Supplier_user') -> where(array('supplier_id' => array('in', $this->_get('id')))) -> delete();
		parent::delete();
	}
	//显示修改页
    public function edit() {
        if ($this->_get('id')) {
            $map['id'] = array(
                'eq',
                $this->_get('id')
            );
            $this->info = $this->dao->where($map)->find();
			$this->login_name=D('Member')->where('id = '.intval($this->info['member_id']))->getfield('username');
			$this->info['area'] = trim($this->info['area'], ',');
			$this->assign('info', $this -> info);
            $this->display();
        } else {
            $this->error('参数错误');
        }
    }
	public function update(){
		if($_POST['login_name']!=''){
			$member=D('Supplier')->where('id ='.$_POST['id'])->getfield('member_id');
			D('Member')->where('id ='.$member)->save(array('username'=>$_POST['login_name']));
			D('User')->where('member_id ='.$member)->save(array('account'=>$_POST['login_name']));
		}
		$_POST['area'] = ','.implode(',',$_POST['area']).',';
		$baidumap = explode(',', $_POST['baidupoint']);
		$_POST['baidumapX'] = $baidumap[0];
		$_POST['baidumapY'] = $baidumap[1];
		//转存经纬度
		$p = curlRequest('http://api.map.baidu.com/ag/coord/convert?from=0&to=4&x='.$baidumap[0].'&y='.$baidumap[1]);
		$p = json_decode($p, true);
		
		$_POST['lx'] = base64_decode($p['x']);
		$_POST['ly'] = base64_decode($p['y']);
		$_POST['geohash'] = encode_geohash($_POST['lx'],$_POST['ly'], 10);
		parent::update();
	}
	
	//添加管理用户
	public function addUser(){
		$this->dao = D('Supplier_user'); 
		$data['user_id'] = $this->_post('user_id');
		$data['supplier_id'] = $this->_post('sid');
		$info = $this->dao -> where($data) -> find();
		if(!is_array($info)){
			//$this->dao -> create($data);
			$ret = $this->dao -> add($data);
			if($ret !== false){
				$nickname = M('User') -> where(array('id' => $data['user_id'])) -> find();
				$red['status'] = 1;
				$red['data'] = $nickname['nickname'];
				$red['info'] = '添加成功';
				exit(json_encode($red));
			}else{
				$this->error($this->dao -> getError());
			}
		}else{
			$this->error('已经存在这个用户');
		}
	}
	//删除管理用户
	public function delUser(){
		$this->dao = D('Supplier_user');
		$data['user_id'] = $this->_post('user_id');
		$data['supplier_id'] = $this->_post('sid');
		$ret = $this->dao -> where($data) -> delete();
		if($ret !== false){
			$red['status'] = 1;
			$red['data'] = $data['user_id'];
			$red['info'] = '删除成功';
			exit(json_encode($red));
		}else{
			$this->error($this->dao -> getError());
		}
	}
	
	
	
	
	
	
	//异步更新单个字段内容
    public function ajaxUpdate() {
        if ($this->_post('data')) {
            $data = explode(',', $this->_post('data'));
            $id = $data[1];
            $field = $data[0];
            $returndata = array();
            $one = $this->dao->where(array('id' => $id))->find();
            if (!is_array($one)) {
                $returndata['status'] = 0;
            } else {
                if ($one[$field] == 0) {
                    $savedate[$field] = 1;
                } else {
                    $savedate[$field] = 0;
                }
                $re = $this->dao->where(array(
                    'id' => $id
                ))->save($savedate);
                if ($re !== false) {
                    $returndata['status'] = 1;
                } else {
                    $returndata['status'] = 0;
                }
            }
        } else {
            $returndata['status'] = 0;
        }
		if($field == 'status'){
		    $supplieruser = M('Supplier_user') -> where(array('supplier_id' => $id)) -> getField('user_id',true);
			if($supplieruser){
				M('User') -> where(array('id' => array('in', $supplieruser))) -> data(array('status' => $savedate['status'])) -> save();
			}
			$memberid = M('Supplier') -> where(array('id' => $id)) -> getField('member_id');
			$membername=D('Member')->where('id ='.$memberid)->getfield('username');
			if($savedate[$field] == 0){
				$Supplier = M('Supplier') -> where(array('id' => $id)) -> find();
			    D('Member')->changeLevel(array('id' => $memberid, 'level' => 0));
			}else{
				$Supplier = M('Supplier') -> where(array('id' => $id)) -> find();
			    D('Member')->changeLevel(array('id' => $memberid, 'level' => 1));

				//发送用户名和密码
				$pwd = rand(100000, 999999);
				$updatepwd['password'] = md5($pwd);
				M('User') -> where(array('member_id' => $memberid)) -> save($updatepwd);
				
				$user=M('User') -> where(array('member_id' => $memberid)) ->find();
				M('Member') -> where(array('id' => $memberid)) -> save($updatepwd);
				$returnText = "登录地址：http://www.ydzh99.com/Admin";
				$member = M('Member') -> where(array('id' => $memberid)) -> find();
				$msg['first']='你好'.$Supplier['susername'].',注册成功！';
				$msg[0]='http://www.ydzh99.com/Admin';
				$msg[1]=$member['username'];
				$msg[2]=$pwd;
				$msg['remark']='';
				sendWXTempMsg($member['openid'],$msg,'OIrfqCkxuc2s_9y7Ijc2_K3QHNiwCVLUBROnQQwFwqM');
			}
		    $supplieruser = M('Supplier_user') -> where(array('supplier_id' => $id)) -> getField('user_id',true);
		}
        $returndata['data'] = $savedate[$field];
        echo json_encode($returndata);
    }
	
	
	
	
	
	
	
	
}